<template>

  <view class="sms-login-page">
    <view class="Back-icon" style="margin-top: 55rpx;margin-bottom: 107rpx;margin-left: -25rpx;" @click="goBack">
      <uni-icons type="closeempty" size="20"></uni-icons>
    </view>

    <!-- 标题与说明 -->
    <view class="title">短信验证码登录</view>
    <view class="desc">未注册手机验证后自动登录并注册账户</view>


    <!-- 手机号输入区域 -->
    <view class="input-group">
      <view class="country-code">
        <text>+86</text>
        <view class="sanjiao"></view>
      </view>
      <input class="phone-input" type="number" placeholder="请输入您的手机号" v-model="phoneNumber" @input="handlePhoneInput"
        :class="{ 'error-border': showPhoneError }" />
    </view>


    <!-- 发送验证码按钮 -->
    <button class="send-btn" :disabled="!hasInput || isCountingDown" @click="sendSms"
      :class="{ 'send-btn-active': hasInput && !isCountingDown }">
      {{ isCountingDown ? countdownText : '发送验证码' }}
    </button>

    <!-- 协议勾选 -->
    <view class="agreement">
      <view class="custom-checkbox" @click="toggleAgreement">
        <image 
          class="checkbox-image" 
          :src="isAgreed ? '/static/image/codev.png' : '/static/image/codee.png'" 
          mode="aspectFit"
        />
        <text class="agreement-text">我已阅读并同意</text>
      </view>

      <!-- 点击打开协议弹窗 -->
      <text class="protocol-link" @click="openProtocolPopup('userProtocol')">《用户协议》</text>
      <text class="separator">《</text>
      <text class="protocol-link" @click="openProtocolPopup('privacyPolicy')">隐私政策</text>
      <text class="separator">》</text>
    </view>

    <!-- 手机号错误提示 -->
    <view class="error-tip" v-if="showPhoneError"><text>{{ phoneErrorMsg }}</text></view>


    <!-- 协议内容弹窗 -->
    <uni-popup ref="protocolPopup" type="bottom">
      <view class="popup-container">
        <!-- 弹窗标题 + 关闭按钮 -->
        <view class="popup-header">
          <text class="popup-title">{{ popupTitle }}</text>
          <uni-icons type="closeempty" size="22" class="close-icon" @click="closeProtocolPopup"></uni-icons>
        </view>
        <!-- 协议内容 - Using rich-text -->
        <scroll-view class="popup-content" scroll-y>
          <rich-text :nodes="getProtocolContent()"></rich-text>
        </scroll-view>
      </view>
    </uni-popup>

  </view>
</template>
<script>
import { request, initBaseUrl, getFullImageUrl } from '../../utils/request';
export default {
  data() {
    return {
      phoneNumber: '', // 绑定的手机号
      isPhoneValid: false, // 手机号是否有效
      hasInput: false, // 是否有输入内容，用于控制发送按钮状态
      isAgreed: false, // 协议是否勾选
      showPhoneError: false, // 是否显示手机号错误提示
      phoneErrorMsg: '', // 手机号错误提示消息
      debounceTimer: null,
      userProtocolContent: '', // 用户协议内容
      privacyPolicyContent: '', // 隐私政策内容
      popupTitle: '', // 弹窗标题
      popupType: '', // 当前显示的协议类型（userProtocol / privacyPolicy）,
      isCountingDown: false, // 倒计时状态
      countdownText: '发送验证码' // 按钮文本
    }
  },
  async onLoad() {
    try {
      // 获取用户协议内容
      const termsResponse = await request({
        url: '/Agreement/terms',
        method: 'GET'
      });
      this.userProtocolContent = termsResponse.data.content || '';
      this.userProtocolTitle = termsResponse.data.title || '用户协议';

      // 获取隐私政策内容
      const privacyResponse = await request({
        url: '/Agreement/privacy',
        method: 'GET'
      });
      this.privacyPolicyContent = privacyResponse.data.content || '';
      this.privacyPolicyTitle = privacyResponse.data.title || '隐私政策';
    } catch (error) {
      console.error('获取协议内容失败', error);
      // 使用默认内容
      this.userProtocolContent = this.getEmptyProtocolContent('用户协议');
      this.privacyPolicyContent = this.getEmptyProtocolContent('隐私政策');
    }
  },

  methods: {
    // 处理手机号输入，仅更新hasInput状态
    handlePhoneInput() {
      // 清除之前的定时器
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }

      // 设置新的定时器，300ms后执行逻辑
      this.debounceTimer = setTimeout(() => {
        // 更新输入状态
        this.hasInput = this.phoneNumber.length > 0;
        
        console.log('是否有输入:', this.hasInput);
      }, 300); // 300ms防抖延迟，可根据需求调整
    },
    // 添加协议勾选变化处理
    onAgreementChange(e) {
      // 返回的是数组，包含所有被选中的checkbox的value值
      this.isAgreed = e.detail.value.includes('agree');
      // console.log('协议状态:', this.isAgreed);
    },
    
    // 切换协议勾选状态
    toggleAgreement() {
      this.isAgreed = !this.isAgreed;
      // console.log('协议状态:', this.isAgreed);
    },

    // 发送验证码逻辑，对接实际接口
    async sendSms() {
      // 点击时验证手机号格式
      const reg = /^1[3-9]\d{9}$/;
      this.isPhoneValid = reg.test(this.phoneNumber);
      
      // 清除之前的错误状态
      this.showPhoneError = false;
      this.phoneErrorMsg = '';
      
      // 如果手机号格式不正确，显示错误提示
      if (!this.isPhoneValid) {
        this.showPhoneError = true;
        this.phoneErrorMsg = '手机号格式错误，请输入正确的格式';
        setTimeout(() => {
          this.showPhoneError = false;
        }, 3500);
        return; // 阻止继续执行
      }
      
      if (this.isPhoneValid && this.isAgreed) {
        // 调用发送验证码接口
        uni.showLoading({ title: '发送中...' });
        try {
          // 实际POST请求
          const response = await request({
            url: 'Sms/send',
            method: 'POST',
            data: {
              mobile: this.phoneNumber, // 发送手机号
              event: 'login' // 事件类型
            },
          });

          uni.hideLoading();
          console.log('发送验证码响应:', response); // 查看响应数据
          // 处理接口返回结果
          if (response.code === 0) {
            // 显示后台返回的消息（即使是提示安装插件）
            uni.showToast({ title: response.msg, icon: 'none' });
            // 启动倒计时
            this.startCountdown();
            // 跳转到验证码输入页面
            setTimeout(() => {
              uni.navigateTo({ url: `/pages/pageLogin/code?phone=${encodeURIComponent(this.phoneNumber)}` });
            }, 1500);
          } else {
            uni.showToast({ title: response.msg || '发送失败', icon: 'none' });
          }
        } catch (error) {
          uni.hideLoading();
          uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
          console.error('发送验证码失败:', error);
        }
      } else {
        if (!this.isAgreed) {
          uni.showToast({ title: '请勾选协议', icon: 'none' });
        }
      }
    },

    // 添加倒计时方法
    startCountdown() {
      let countdown = 60;
      const timer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
          clearInterval(timer);
          this.isCountingDown = false;
        } else {
          this.isCountingDown = true;
          this.countdownText = `${countdown}秒后重新发送`;
        }
      }, 1000);
    },

    // 打开协议弹窗
    openProtocolPopup(type) {
      this.popupType = type;
      this.popupTitle = type === 'userProtocol'
        ? this.userProtocolTitle || '用户协议'
        : this.privacyPolicyTitle || '隐私政策'; // 使用动态标题
      this.$refs.protocolPopup.open();
    },

    // 关闭协议弹窗
    closeProtocolPopup() {
      this.$refs.protocolPopup.close();
    },

    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页
      });
    },

    // 获取协议内容
    getProtocolContent() {
      const content = this.popupType === 'userProtocol' 
        ? this.userProtocolContent 
        : this.privacyPolicyContent;
      
      // 如果内容是HTML字符串，直接返回；如果是空的，返回默认内容
      if (content && typeof content === 'string') {
        return content;
      }
      
      return this.getEmptyProtocolContent(this.popupTitle);
    },
    
    // 获取空协议的默认内容
    getEmptyProtocolContent(title) {
      return `
        <div>
          <h1 style="font-size: 36rpx; font-weight: bold; margin-bottom: 30rpx;">${title}</h1>
          <p style="font-size: 28rpx; line-height: 1.6; margin-bottom: 20rpx;">
            加载协议内容失败，请稍后再试。
          </p>
        </div>
      `;
    }
  }
}	
</script>

<style lang="scss" scoped>
.sms-login-page {
  padding: 60rpx;
  background-color: #fff;
  min-height: 100vh;
  box-sizing: border-box;

  // 标题
  .title {
    font-family: Source Han Sans CN;
    font-weight: 530;
    font-size: 54rpx;
    color: #0E1C37;
    line-height: 26rpx;
    margin-bottom: 35rpx;
  }

  // 说明文字
  .desc {
    font-weight: 400;
    font-size: 30rpx;
    color: #A3A6B7;
    line-height: 26rpx;
    margin-bottom: 100rpx;
  }

  // 输入区域	
  .input-group {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;
    padding: 6rpx 0rpx;
    margin-bottom: 200rpx;

    .country-code {
      display: flex;
      align-items: center;
      border-right: 1px solid #eee;
      padding-right: 20rpx;

      .sanjiao {
        width: 0;
        height: 0;
        border-top: 8rpx solid #0E1C37;
        /* 保留上边框 */
        border-left: 8rpx solid transparent;
        /* 左侧透明边框 */
        border-right: 8rpx solid transparent;
        /* 右侧透明边框 */
        border-bottom: 0;
        /* 取消下边框 */
        margin-left: 20rpx;
      }

      text {
        font-size: 32rpx;
        color: #0E1C37;
      }
    }



    // 输入框错误边框
    .error-border {
      font-size: 30rpx;
      color: #F71737;
    }

    .phone-input {
      flex: 1;
      height: 80rpx;
      font-size: 28rpx;
      padding-left: 20rpx;
    }
  }

  // 发送验证码按钮
  .send-btn {
    width: 97%;
    height: 80rpx;
    line-height: 80rpx;
    background: #D0D4D7;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #888B9A;

    margin-bottom: 30rpx;

    &:disabled {
      opacity: 0.6;
    }
  }

  .send-btn-active {
    background-color: #BEFF32; // 绿色背景
    color: #0E1C37; // 白色文字
    font-weight: 500;
  }


  // 协议区域
  .agreement {
    display: flex;
    align-items: center;
    font-size: 22rpx;
    color: #A3A6B7;

    .custom-checkbox {
      display: flex;
      align-items: center;
    }

    .checkbox-image {
      width: 32rpx;
      height: 32rpx;
      margin-right: 10rpx;
    }

    .agreement-text {
      font-size: 22rpx;
      color: #A3A6B7;
    }

    .protocol-link {
      color: #1890FF;
      text-decoration: none;
      margin: 0 4rpx;
    }

    .separator {
      margin: 0 4rpx;
    }
  }

  // 手机号错误提示
  .error-tip {
    position: fixed;
    bottom: 270rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 500rpx;
    height: 86rpx;
    background: #404040;
    box-shadow: 0rpx 9rpx 13rpx 0rpx rgba(64, 64, 64, 0.27);
    border-radius: 16rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .error-tip text {
    font-weight: 500;
    font-size: 28rpx;
    color: #FFFFFF;
  }
}

/* 协议弹窗样式 */
.popup-container {
  width: 100%;
  background: #FFFFFF;
  border-radius: 35rpx 35rpx 0rpx 0rpx;
  /* 关键修改1：设置固定高度（建议使用vh单位） */
  height: 70vh; // 70%视窗高度，可根据需求调整
  /* 关键修改2：启用flex布局控制内部滚动 */
  display: flex;
  flex-direction: column;
}

.popup-header {
  padding: 10rpx 40rpx;
  background-color: #fff;
  border-radius: 35rpx 35rpx 0rpx 0rpx;
  border-bottom: 1px solid #eee;
  /* 固定标题栏高度 */
  height: 100rpx;
  flex-shrink: 0; // 防止标题栏被压缩
  font-size: 36rpx;
  font-weight: bold;
  color: #0E1C37;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.popup-content {
  /* 关键修改3：允许内容区域滚动 */
  overflow-y: auto;
  /* 关键修改4：填充剩余空间 */
  flex: 1;
}
</style>